import Web from "./env/web"
import WxMp from "./env/wxMp"
import WxWeb from "./env/wxWeb"
import Abc from "./env/abc"
import Cib from "./env/cib"
import Ysf from "./env/ysf"
import Efz from "./env/efz"
import Boc from "./env/boc"
import Gat from "./env/gat"
import Pab from "./env/pab"
import Yzf from "./env/yzf"
import Cmbc from "./env/cmbc"
import Icbc from "./env/icbc"
import Ibl from "./env/ibl"
import Ulejf from "./env/ulejf"
import { isFunction } from "@/utils/check"
import { useWebEnv, useWebEvn } from "./utils"

const evns = { mp: WxMp, wxWeb: WxWeb, abc: Abc, cib: Cib, web: Web, ysf: Ysf, cmbc: Cmbc, boc: Boc, efz: Efz, gat: Gat, icbc: Icbc, pab: Pab, yzf: Yzf, ibl: Ibl, ulejf: Ulejf }

const success = (params, data) => {
  isFunction(params.success) && params.success(data)
  isFunction(params.complete) && params.complete()
}
const fail = (params, err) => {
  isFunction(params.fail) && params.fail(err)
  isFunction(params.complete) && params.complete()
}
class Auth {
  constructor(config = {}) {
    this.sdk = null
    this.isReady = false
    this.config = config
    this.webEnv = useWebEnv()
    this.webEvn = useWebEvn()
  }
  ready(params = {}) {
    return new Promise((resolve, reject) => {
      try {
        if (evns[this.webEvn]) {
          this.sdk = new evns[this.webEvn](this.config)
          this.sdk
            .ready()
            .then(() => {
              this.isReady = true
              resolve(this)
              success(params, this)
            })
            .catch((error) => {
              reject(error)
              fail(params, error)
            })
        } else {
          reject({ errMsg: "未正确获取到evn环境!" })
          fail(params, { errMsg: "未正确获取到evn环境!" })
        }
      } catch (error) {
        reject(error)
        fail(params, error)
      }
    })
  }

  login(params = {}) {
    return new Promise(async (resolve, reject) => {
      try {
        if (this.isReady) {
          if (evns[this.webEvn]) {
            await this.sdk.login()
            this.sdk.setLoginTime()
            success(params, this)
            resolve(this)
          } else {
            fail(params, { errMsg: "未正确获取到evn环境!" })
            reject({ errMsg: "未正确获取到evn环境!" })
          }
        } else {
          fail(params, { errMsg: "环境未初始化,请检查!" })
          reject({ errMsg: "环境未初始化,请检查!" })
        }
      } catch (error) {
        fail(params, error)
        reject(error)
      }
    })
  }
}

export default Auth
